package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class TaskPoolConfig {

    @Bean("taskExecutor")
    public Executor taskExecutor(){
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(8);//核心线程数
        taskExecutor.setMaxPoolSize(16);//最大线程数
        taskExecutor.setQueueCapacity(200);//queueCapacity：当核心线程都在跑任务，还有多余的任务会存到此处。
        taskExecutor.setKeepAliveSeconds(60);//允许线程的空闲时间60秒：当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        taskExecutor.setThreadNamePrefix("taskExecutor--");//线程池中的线程的名称前缀
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);//销毁开关
        taskExecutor.setAwaitTerminationSeconds(60);//该方法用来设置线程池中任务的等待时间,如果超过这个时间还没有销毁就强制销毁
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//CallerRunsPolicy让调用者去执行它
        return taskExecutor;
    }


}